﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.Xpo;
using Aij1.Model;
using DevExpress.Data.Filtering;

namespace RebuildKeywords
{
    /// <summary>
    /// 将A_Article表中的Keywords字段转换成A_ArticleKeyword中的文章-关键词关联记录
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            UnitOfWork uow = XpoHelper.GetNewUnitOfWork();

            XPCollection<A_Article> articles = new XPCollection<A_Article>(uow);
            Console.WriteLine("共有{0}篇文章等待处理.", articles.Count);

            foreach (var article in articles)
            {
                Console.WriteLine("处理文章{0}...", article.Oid);
                rebuldKeywords(article);
            }

            uow.CommitChanges();
            Console.WriteLine("处理完成! 按回车退出.");
            Console.ReadLine();
        }

        private static void rebuldKeywords(A_Article article)
        {
            if (String.IsNullOrEmpty(article.Keywords)) return;
            string[] keywords = article.Keywords.Split(';');

            foreach (string key in keywords)
            {
                A_Keyword keyword = article.Session.FindObject<A_Keyword>(CriteriaOperator.Parse("Title=?", key));
                if (keyword == null) return;

                A_ArticleKeyword ak = new A_ArticleKeyword(article.Session)
                {
                    KeywordId = keyword,
                    ArticleId = article,
                };
            }
        }
    }
}
